from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from rest_framework.viewsets import GenericViewSet
from .models import User
from rest_framework.generics import CreateAPIView,GenericAPIView,RetrieveAPIView
from .serializers import RegisterCreateUserSerializer, UserCenterInfoSerializer, AddressSerializer, \
    AddressTitleSerializer

class RegisterUserNameView(APIView):

    """
    GET     /users/xxx/usernames/(?P<username>\w{5,20})/count/
    """

    def get(self,request,username):

        count = User.objects.filter(username=username).count()

        context = {
            'count':count,
            'username':username
        }

        return Response(context)


# 1.我们用到序列化器 所以排除APIView
# 2.因为数据要入库 所以我们选择第三级视图
class RegisterCreateUserView(CreateAPIView):
    """
    POST /users/
    1.获取前端提交的数据，username password password2 mobile sms_code allow
    2.对提交的数据进行校验
    3.保存入库
    """
    # 我的需求是将数据入库
    serializer_class = RegisterCreateUserSerializer

    # query_set 因为我们的这个视图只是实现了数据的增加操作 没有查询数据
    # 所以 CreateAPIView 没有机会调用get_queryset 方法

    # queryset = User.objects.all()
    # get 方法是获取所有用户信息
    # def get(self,request):


from rest_framework.permissions import IsAuthenticated
class UserCenterInfoView(CreateAPIView):
    """
    1.访问个人中心必须是登陆用户，IsAuthenticated只能是认证用户
    2.得到指定用户的信息，得到用户信息的话，用户信息是模型，模型转换为json

    """
    # 必须是登陆用户
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    def get(self,request):

        user = request.user

        serializer = self.get_serializer(instance=user)

        return Response(serializer.data)


class UserCenterInfo2View(RetrieveAPIView):
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    # 重写方法　返回　用户数据
    def get_object(self):
        return self.request.user


"""
    1.当用户点击设置邮箱的时候，让用户输入邮箱，输入邮箱之后，我们要保存邮箱信息
    2.我们需要发送一个激活邮件给用户
    3.我们需要记住　邮件的激活状态
    4.如何发送邮件　邮件的url　和　如何激活邮件
"""
from rest_framework.generics import UpdateAPIView
from .serializers import EmailUpdateSerializer
class EmailUpdateView(UpdateAPIView):
    """
    1.把用户的信息提交过来
    2.更新的User的email字段就可以，肯定对email进行校验

    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailUpdateSerializer

    def get_object(self):
        return self.request.user


class VerityEmailView(APIView):
    """
    GET    /users/emails/verifications?token=xxx
    GET    /users/emails/token/
    # 1.通过GET方式，把token给返回回来
    # 2.获取token，检测token
    # 3.得到　user.id 根据　userid，修改状态就可以了

    """

    def get(self,request):

        # 1. 通过GET方式 把token给我返回回来
        token = request.query_params.get('token')
        if token is None:
            return Response(status=400)
        # 2. 获取token,检测token,得到 user.id 根据userid, 返回用户模型
        user = User.user_by_token(token)
        # 3. ,修改状态就可以了
        if user is None:
            return Response(status=400)
        else:
            #修改状态就可以了
            user.email_active=True
            user.save()

        return Response({'message':'ok'})



class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    from rest_framework.decorators import action

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

# APIView
# GenericAPIView
# CreateAPIView
from .serializers import UserHistorySerializer,SKUSerializer
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
from goods.models import SKU
class UserHistoryView(GenericAPIView):
    """
    1.我们只记录登陆用户的历史记录，没有登陆的用户是不能访问该接口的
    2.前端发送一个请求，这个请求要有用户信息和商品id
    3.判断商品id是否正确
    4.将记录信息保存在Redis中

    POST     /users/histories

    """

    # 添加权限
    permission_classes = [IsAuthenticated]

    serializer_class = UserHistorySerializer

    def post(self,request):
        # 创建序列化器，对数据进行校验
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'message':'ok'})


    def get(self,request):
        """
        1.既然是用户的历史记录，肯定是登陆用户
        2.用户的历史记录在redis中，我们从redis中获取数据
        3.根据id查询商品信息
        4.将模型转换为JSON
        """
        user = request.user
        #1.连接redis
        redis_conn = get_redis_connection('history')
        #2.获取指定用户的历史记录
        ids = redis_conn.lrange('history_%s'%user.id,0,5)
        #3.定义一个列表来接收查询好的数据
        skus = []
        for id in ids:
            sku = SKU.objects.get(pk=id)
            skus.append(sku)
        #4.将模型转换为JSON
        # skus = [SKU,SKU,SKU]
        serializer = SKUSerializer(skus,many=True)

        return Response(serializer.data)

from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登陆的数据进行验证
        response = super().post(request)

        #如果用户登陆成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登陆成功
            user = serializer.validated_data.get('user')
            # 合并购物车
            response = merge_cookie_to_redis(request,user,response)

        return response

















